package com.igorkundovic.guitarstab.pages;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import org.apache.tapestry5.annotations.ApplicationState;
import org.apache.tapestry5.annotations.BeginRender;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.beaneditor.Validate;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.upload.services.UploadedFile;

import com.igorkundovic.guitarstab.Artist;
import com.igorkundovic.guitarstab.Genre;
import com.igorkundovic.guitarstab.User;
import com.igorkundovic.guitarstab.Tab;
import com.igorkundovic.guitarstab.beans.ArtistBean;
import com.igorkundovic.guitarstab.beans.TabBean;
import com.igorkundovic.guitarstab.service.TabService;

public class Upload {

	@ApplicationState
	@Property
	private User user;
	private boolean userExists;
	@Property
	private UploadedFile file;
	@Inject
	private TabService tabservice;
	@Property
	private TabBean tab;
	@Property
	@Persist
	private Artist artist;
	@Persist
	@Validate(value="required")
	@Property
	private Genre _type;
	
	
	

	public Object onActivate(){
		artist=new ArtistBean();
		if(userExists){
			return null;
		}
		
		return Welcome.class;
	}
	
	@OnEvent(value = "submit",component="upload")
	public Object onSuccess(){
		File copied=new File("src\\main\\webapp\\tabs\\" + file.getFileName());
		System.out.println("IME FAJLA,BRE:"+file.getFileName());
		if(!copied.exists()){
		file.write(copied);
		String name=file.getFileName();
		String path=file.getFilePath();
		TabBean tab=new TabBean();
		tab.setName(name);
		tab.setPath(path);
		tab.setUser(user);
		tab.setArtist(artist);
		tab.setGenre(_type);
		System.out.println(tab.getName()+" "+tab.getPath()+" "+tab.getUser().getUserName());
		tabservice.save(tab);
		return this;
		}
		else{
			return DuplicateUpload.class;
		}
		
	}
	
	
	

	
	
}
